package xyz.lwm.lazycat.netpipe.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.annotation.Destroy;
import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.beans.AppRunner;
import xyz.lwm.lazycat.beans.BeanLifecycle;
import xyz.lwm.lazycat.netpipe.common.endec.GzipCodec;
import xyz.lwm.lazycat.netpipe.common.endec.MessageCodec;
import xyz.lwm.lazycat.netpipe.common.msgs.MessageHandler;
import xyz.lwm.lazycat.netpipe.common.msgs.MessageHandlerRegistry;
import xyz.lwm.lazycat.netpipe.common.serial.SerialType;
import xyz.lwm.lazycat.netpipe.common.serial.Serialization;
import xyz.lwm.lazycat.netpipe.common.serial.SerializationFactory;
import xyz.lwm.lazycat.netpipe.setting.NetpipeServerSetting;

import java.util.List;

/**
 * <h3>Netpipe Server</h3>
 * data forward
 *
 * @author lwm
 */
@Bean
@Slf4j
public class NetpipeServer implements AppRunner, BeanLifecycle {

    private final ServerBootstrap serverBootstrap = new ServerBootstrap();

    private final NioEventLoopGroup serverBossGroup = new NioEventLoopGroup();

    private final NioEventLoopGroup serverWorkerGroup = new NioEventLoopGroup();

    private final Serialization serialization = SerializationFactory.getSerialization(SerialType.PROTOSTUFF);

    @Inject
    private NetpipeServerSetting serverSetting;

    @Inject
    private MessageHandlerRegistry messageHandlerRegistry;

    @Inject
    private List<MessageHandler> messageHandlers;

    @Override
    public void postConstruct() {
        for (MessageHandler handler : messageHandlers) {
            messageHandlerRegistry.register(handler.getMsgType(), handler);
        }
    }

    @SneakyThrows
    @Override
    public void run(String[] args) {
        serverBootstrap.group(serverBossGroup, serverWorkerGroup)
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new GzipCodec());
                        // 固定帧长解码器
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4));
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        // 自定义协议编解码器
                        ch.pipeline().addLast(new MessageCodec(serialization));
                        // 添加服务端处理器
                        ch.pipeline().addLast(new ServerHandler());
                    }
                }).bind(serverSetting.getHost(), serverSetting.getPort()).addListener(future -> {
                    if (future.isSuccess()) {
                        log.info("Netpipe Server started successfully, listening on " + serverSetting.getHost() + ":" + serverSetting.getPort());
                    } else {
                        log.error("Netpipe Server start failed, listening on " + serverSetting.getHost() + ":" + serverSetting.getPort());
                    }
                }).sync();
    }

    @Destroy
    public void stop() {
        serverBossGroup.shutdownGracefully();
        serverWorkerGroup.shutdownGracefully();
    }

}